﻿using IGL_Talk_Win8.Model;
using IGL_Talk_Win8.Utils;
using System;
using System.Threading;
using Windows.UI.Xaml.Controls;
using WinRTXamlToolkit.Controls.Extensions;

// The User Control item template is documented at http://go.microsoft.com/fwlink/?LinkId=234236

namespace IGL_Talk_Win8.Controls
{
    public sealed partial class Messages : UserControl
    {
        private SynchronizationContext synchronizationContext;
        private bool blockSend = false;

        public Messages()
        {
            this.InitializeComponent();

            synchronizationContext = SynchronizationContext.Current;
            if (synchronizationContext == null)
            {
                throw new Exception("No synchronization context was specified and no default synchronization context was found.");
            }

            listMessages.ItemsSource = ChatConnection.Instance.Messages;
            ChatConnection.Instance.Messages.CollectionChanged += Messages_CollectionChanged;
        }

        private void Messages_CollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
        {
            synchronizationContext.Post((arg) =>
            {
                var scrollViewer = listMessages.GetFirstDescendantOfType<ScrollViewer>();
                scrollViewer.ChangeView(0, scrollViewer.ScrollableHeight + 500, scrollViewer.ZoomFactor);
            }, null);
        }

        private void cmdSend_Click(object sender, Windows.UI.Xaml.RoutedEventArgs e)
        {
            ChatConnection.Instance.SendMessage(txtMessage.Text);
            txtMessage.Text = string.Empty;
        }

        private void txtMessage_KeyDown(object sender, Windows.UI.Xaml.Input.KeyRoutedEventArgs e)
        {
            if (e.Key == Windows.System.VirtualKey.Enter && !blockSend)
            {
                cmdSend_Click(null, null);
                blockSend = true;
            }
        }

        private void txtMessage_KeyUp(object sender, Windows.UI.Xaml.Input.KeyRoutedEventArgs e)
        {
            if (e.Key == Windows.System.VirtualKey.Enter)
            {
                blockSend = false;
            }
        }
    }
}